<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllWorkerService, addWorkerService, updateWorkerService, deleteWorkerService } from '@/api/worker'
import { getAllDepartmentService } from '@/api/department'


const tableData = reactive([])

const search = ref('')
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase()) || data.workerId.toLowerCase().includes(search.value.toLowerCase())
    )
)


const pageNum = ref(1)
const total = ref(20)
const pageSize = ref(10)

async function getWorkerList() {
    tableData.length = 0
    let result = await getAllWorkerService(pageNum.value, pageSize.value)
    if (result.code === 0) {
        total.value = result.data.total
        for (let i = 0; i < result.data.items.length; i++) {
            tableData.push(result.data.items[i])
        }
    } else {
        console.log(res.message)
    }
}
getWorkerList()


const onSizeChange = (size) => {
    pageSize.value = size
    getWorkerList()
}
const onCurrentChange = (num) => {
    pageNum.value = num
    getWorkerList()
}

const departmentData = reactive([])

const getAllDepartment = async () => {
    departmentData.length = 0
    let result = await getAllDepartmentService()
    for (let i = 0; i < result.data.length; i++) {
        departmentData.push(result.data[i])
    }
}

const dialogFormVisible = ref(false)

const openAddDialog = () => {
    getAllDepartment()
    dialogFormVisible.value = true
}


var addForm = reactive({
    name: '',
    phoneNumber: '',
    id: '',
    email: '',
    department: ''
})

const checkMobile = (rule, value, cb) => {
    const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
    if (regMobile.test(value)) {
        //合法的手机号
        return cb();
    }
    //手机号不合法
    cb(new Error('请输入合法的手机号！'));
}
const checkId = (rule, value, callback) => {
    const reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/;
    const card = reg.test(value);
    if (!card) {
        callback(new Error("身份证号格式有误！"));
    } else {
        callback();
    }
}
const rules = {
    department: [{ required: true, message: '房间号不可为空！', trigger: 'blur' }],
    name: [{ required: true, message: '姓名不可为空！', trigger: 'blur' }],
    phoneNumber: [
        { required: true, message: '手机号不可为空！', trigger: 'blur' },
        { validator: checkMobile, trigger: ['blur', 'change'] }
    ],
    email: [
        { required: true, message: '邮箱不可为空！', trigger: 'blur' }
        ,
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    id: [
        { required: true, message: '身份证号不可为空！', trigger: 'blur' },
        { validator: checkId, trigger: ['blur', 'change'] }
    ]
}

const addWorker = async () => {
    // console.log(addForm.roomNumber)
    await addWorkerService(addForm)
    ElMessage.success('新增工作人员成功')
    getWorkerList()
    addForm.name = ''
    addForm.phoneNumber = ''
    addForm.id = ''
    addForm.email = ''
    addForm.department = ''
    dialogFormVisible.value = false
}


const deleteWorker = async (workerId) => {
    await deleteWorkerService(workerId)
    ElMessage.success('删除成功')
    getWorkerList()
}

const updataForm = reactive({
    workerId: '',
    name: '',
    phoneNumber: '',
    id: '',
    email: '',
    department: ''
})

const updataDialogFormVisible = ref(false)

const handleEdit = (row) => {
    updataForm.workerId = row.workerId
    updataForm.name = row.name
    updataForm.phoneNumber = row.phoneNumber
    updataForm.id = row.id
    updataForm.email = row.email
    updataForm.department = row.department

    getAllDepartment()
    updataDialogFormVisible.value = true
}

const updateWorker = async () => {
    await updateWorkerService(updataForm)
    ElMessage.success('修改成功')
    getWorkerList()
    updataDialogFormVisible.value = false
}

</script>



<template>
    <div style="width: 100%;padding:25px;">
        <div style="display: flex;padding-bottom: 20px;padding-top: 10px;">
            <el-button type="primary" @click="openAddDialog"
                style="width: 70px;background-color: rgb(19, 179, 232);color: white;">添加用户</el-button>
            <el-input v-model="search" placeholder="搜索用户信息" style="width: 200px;margin-left:100vh;" />
        </div>
        <el-table :data="filterTableData" border stripe style="min-width:calc(100vh - 200px)">
            <el-table-column label="工号" prop="workerId" sortable />
            <el-table-column label="姓名" prop="name" sortable />
            <el-table-column label="部门" prop="department" sortable />
            <el-table-column label="手机号" prop="phoneNumber" />
            <el-table-column label="身份证号" prop="id" />
            <el-table-column label="邮箱" prop="email" />
            <el-table-column label="操作" align="center" width='200px'>
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled" icon-color="red"
                        title="确认要删除此工作人员信息吗？" @confirm="deleteWorker(scope.row.workerId)">
                        <template #reference>
                            <el-button size="small" type="danger">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin: 10px 0;">
            <el-pagination v-model:current-page="pageNum" v-model:page-size='pageSize' :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="onSizeChange"
                @current-change="onCurrentChange" />
        </div>
    </div>


    <el-dialog v-model="dialogFormVisible" title="新增工作人员信息" width="500">
        <el-form :model="addForm" label-width="90px" :rules="rules" ref="form">
            <!-- <el-form-item label="门牌号" prop="roomNumber">
                <el-cascader v-model="cascader" :options="options" :props="props" />
            </el-form-item> -->
            <el-form-item label="姓名" prop="name">
                <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="部门" prop="department">
                <el-select v-model="addForm.department" placeholder="Select" style="width: 240px">
                    <el-option v-for="item in departmentData" :key="item.department" :label="item.department" :value="item.department" />
                </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
                <el-input v-model="addForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="身份证号" prop="id">
                <el-input v-model="addForm.id" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addWorker">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="updataDialogFormVisible" title="修改工作人员信息" width="500">
        <el-form :model="updataForm" label-width="90px" :rules="rules">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="updataForm.name" />
            </el-form-item>
            <el-form-item label="部门" prop="department">
                <el-select v-model="updataForm.department" placeholder="Select" style="width: 240px">
                    <el-option v-for="item in departmentData" :key="item.department" :label="item.department" :value="item.department" />
                </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
                <el-input v-model="updataForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="身份证号" prop="id">
                <el-input v-model="updataForm.id" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="updataForm.email" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updataDialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="updateWorker">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>


</template>
